import csv
import os
from DrissionPage import ChromiumPage

class DouYinGet:
    def __init__(self,search_name):
        self.page = ChromiumPage()
        self.name = []
        self.search_name = search_name


    def login(self):
        self.page.get('https://www.douyin.com/hot')

    def create_csv(self):
        headers = ['热搜内容']
        csv_path = f'E:/my_python_project/zaodiaDP/csv_file/{self.search_name}.csv'
        # 检查文件是否存在
        if os.path.exists(csv_path):
            print(f'文件已存在:{csv_path}')
            # return
        else:
            os.makedirs(os.path.dirname(csv_path), exist_ok=True)

        # 写入csv文件
        with open(csv_path, 'w', newline='', encoding='utf-8-sig') as f:
            writer = csv.writer(f)
            writer.writerow(headers)

    def get_data(self):
        name_eles = self.page.eles('xpath=//a[@class="uz1VJwFY NI7Pd7lt"]')
        for name_ele in name_eles:
            self.name.append(name_ele.text)

    def write_csv(self):
        csv_path = f'E:/my_python_project/zaodiaDP/csv_file/{self.search_name}.csv'
        with open(csv_path, 'a', newline='', encoding='utf-8-sig') as f:
            writer = csv.writer(f)
            for i in range(len(self.name)):
                writer.writerow([self.name[i]])

    def main(self):
        self.login()
        self.create_csv()
        self.get_data()
        self.write_csv()


if __name__ == '__main__':
    search_name = input('请输入文件名')
    DouYinGet.main()

    